package com.yy.util.bitmap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by Administrator on 2015/5/4.
 */
public abstract class BitmapHelper {

    public abstract Bitmap decode(BitmapFactory.Options options);

    /**
     * 加载缩略图
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public Bitmap decodeSampleBitmap(int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        //BitmapFactory.decodeStream()
        decode(options);
        options.inSampleSize = calculateSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return decode(options);
    }

    public Bitmap decodeStream(int reqWidth, int reqHeight, final InputStream stream) {
       return new BitmapHelper() {
            @Override
            public Bitmap decode(BitmapFactory.Options options) {
                return BitmapFactory.decodeStream(stream, null, options);
            }
        }.decodeSampleBitmap(reqWidth, reqHeight);
    }

    public static InputStream bitmap2InputStream(Bitmap bitmap) {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        final InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
        return inputStream;
    }

    private int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        final int width = options.outHeight;
        final int height = options.outHeight;
        int inSampleSize = 1;

        if(height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}
